package com.yyn.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yyn.seckill.entity.SeckillOrder;
import com.yyn.seckill.mapper.SeckillOrderMapper;
import com.yyn.seckill.service.SeckillOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yyn.seckill.util.MD5Util;
import com.yyn.seckill.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 秒杀订单表 服务实现类
 * </p>
 *
 * @author yyn
 * @since 2023-01-21
 */
@Service
public class SeckillOrderServiceImpl extends ServiceImpl<SeckillOrderMapper, SeckillOrder> implements SeckillOrderService {
@Autowired
private RedisTemplate redisTemplate;
    /**
     * orderId:成功
     * -1：失败
     * 0：排队中
     * @param userId
     * @param goodsId
     * @return
     */
    @Override
    public Long getResult(long userId, long goodsId) {
//        1、查询秒杀订单时候有数据
        LambdaQueryWrapper<SeckillOrder> seckillOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        seckillOrderLambdaQueryWrapper.eq(SeckillOrder::getUserId,userId);
        seckillOrderLambdaQueryWrapper.eq(SeckillOrder::getGoodsId,goodsId);
        SeckillOrder seckillOrder = this.getOne(seckillOrderLambdaQueryWrapper);
        if(seckillOrder!=null){
            return seckillOrder.getOrderId();
        }else if(redisTemplate.hasKey("isStockEmpty:"+goodsId)){//当库存<1会存该redis
            return -1L;//无库存
        }else {
            return 0L;//排队
        }
    }

    @Override
    public String createSeckillPath(long userId, long goodsId) {
        String str= MD5Util.md5(UUIDUtil.uuid()+"123456");
//        随机一次性的东西保存到redis中
        redisTemplate.opsForValue().set("seckillpath:"+userId+":"+goodsId,str,60, TimeUnit.SECONDS);
        return str;
    }
}
